//
//  PhotoBrowserViewController.swift
//  WeiBoSwift
//
//  Created by Jacky Sun on 16/5/19.
//  Copyright © 2016年 syf. All rights reserved.
//

import UIKit
import SnapKit
import SVProgressHUD

let CollectionIdentifier = "xxxxxxxxxxxxxxxg"

class PhotoBrowserViewController: UIViewController {

    var currentIndex: Int?
    var img_urls: [NSURL]?
    
    init(index: Int, urls: [NSURL]){
       //MARK -m swift语法规定，必须先初始化本类属性， 在初始化父类
        currentIndex = index
        img_urls = urls
        
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
   
    override func viewDidLoad() {
        super.viewDidLoad()
        view.addSubview(collectionView)
        view.addSubview(closeBtn)
        view.addSubview(saveBtn)
        
        collectionView.frame = view.bounds
         closeBtn.snp_makeConstraints { (make) in
            make.left.equalTo(10)
            make.bottom.equalTo(-10)
            make.width.equalTo(100)
            make.height.equalTo(35)
        }
        
        saveBtn.snp_makeConstraints { (make) in
            make.right.equalTo(-10)
            make.bottom.equalTo(-10)
            make.width.equalTo(100)
            make.height.equalTo(35)
        }

        collectionView.registerClass(PictureBrowserCell.self, forCellWithReuseIdentifier:CollectionIdentifier )
        collectionView.dataSource = self
    }


      func closeVC(){
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    private lazy var closeBtn: UIButton = {
        let btn = UIButton()
        btn.setTitle("关闭", forState: UIControlState.Normal)
        btn.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
        btn.backgroundColor = UIColor.darkGrayColor()
        btn.addTarget(self, action: #selector(PhotoBrowserViewController.closeVC)
, forControlEvents: UIControlEvents.TouchUpInside)
        return btn
    }()
    
    /**
     保存照片
     */
     func saveIMage(){
        print("保存相片")
        
        let cell = collectionView.visibleCells().last as! PictureBrowserCell
       let img = cell.picIMg.image
        UIImageWriteToSavedPhotosAlbum(img!, self, #selector(PhotoBrowserViewController.resultForSavePicture(_:error:info:)), nil)
        
         print(collectionView.visibleCells())
    }
    
    
    //保存照片后的结果回调
      func resultForSavePicture(img: UIImage, error: NSError? , info: AnyObject){
        
        if error == nil{
            SVProgressHUD.showInfoWithStatus("保存相册成功")
        }
        else{
            SVProgressHUD.showErrorWithStatus("保存失败")
        }
    }
    
    private lazy var saveBtn: UIButton = {
        let btn = UIButton()
        btn.setTitle("保存", forState: UIControlState.Normal)
        btn.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
        btn.backgroundColor = UIColor.darkGrayColor()
        
        btn.addTarget(self, action: #selector(PhotoBrowserViewController.saveIMage), forControlEvents: UIControlEvents.TouchUpInside)
        return btn
    }()
    
    // collectionView
    private lazy var collectionView: UICollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: PictureLayout())
}


class PictureLayout: UICollectionViewFlowLayout {
    
    override func prepareLayout() {
        
        itemSize = UIScreen.mainScreen().bounds.size
        minimumLineSpacing = 0
        minimumInteritemSpacing = 0
        scrollDirection = UICollectionViewScrollDirection.Horizontal
        
        collectionView?.bounces = false
        collectionView?.showsHorizontalScrollIndicator = false
        collectionView?.pagingEnabled = true
    }
}


/*
  如果报错 控制器没有 遵守自定义的代理的话， 肯能是你没有使用相应的方法
 */
extension PhotoBrowserViewController : UICollectionViewDataSource, CellIMgClickDelegate{
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int{
        return img_urls?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell
    {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(CollectionIdentifier, forIndexPath: indexPath) as! PictureBrowserCell
        cell.url = img_urls![indexPath.item]
        cell.closeBrowserDelegate = self
        return cell
    }
    
    
    func CellIMgClick(cell: PictureBrowserCell) {
        
        dismissViewControllerAnimated(true, completion: nil)
    }
}
